package com.example.demo.config;

import com.example.demo.security.UserDetailService;
import com.example.demo.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailService my;

    /**
     * 配置认证用户信息和权限
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication().withUser("admin").password("jinxudong").authorities("init", "json", "selectOne", "a");
//        auth.inMemoryAuthentication().withUser("jxd").password("jxd").authorities("init");

        //改取数据库
        auth.userDetailsService(my).passwordEncoder(new PasswordEncoder() {

            // 验证密码
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                String rawPass = Md5Util.md5((String) rawPassword);
                boolean result = rawPass.equals(encodedPassword);
                return result;
            }

            // 加密密码
            public String encode(CharSequence rawPassword) {
                return Md5Util.md5((String) rawPassword);
            }
        });

    }


    /**
     * 配置拦截资源
     *
     * @param http
     * @throws Exception return 200 成功 403 未授权
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //匹配所有请求 匹配不同权限访问不同请求
        //http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
        http.authorizeRequests().antMatchers("/init").hasAnyAuthority("init")
                .antMatchers("/tUser/json").hasAnyAuthority("json")
                .antMatchers("/tUser/selectOne*").hasAnyAuthority("selectOne")
                .antMatchers("/tUser/a").hasAnyAuthority("a")
                .antMatchers("/**").fullyAuthenticated().and().httpBasic()
                .and().cors().disable().csrf().disable();


        /***
         * 改为查数据库
         */
       /* List<Permission> listPermission = permissionMapper.findAllPermission();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http
                .authorizeRequests();
        for (Permission permission : listPermission) {
            authorizeRequests.antMatchers(permission.getUrl()).hasAnyAuthority(permission.getPermTag());
        }
        authorizeRequests.antMatchers("/login").permitAll().antMatchers("/**").fullyAuthenticated().and().formLogin()
                .loginPage("/login").and().csrf().disable();*/
    }


    /**
     * 配置密码非加密
     *
     * @return
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

    public static void main(String[] args) {
        String ss = Md5Util.md5("jxd");
        System.out.println(ss);
    }
}
